import { Form } from 'antd';
import { Rule } from 'antd/lib/form';
import React, { CSSProperties } from 'react';
import InputLimit, { InputLimitProps } from '../InputLimit';
import InputVeriCode, { InputVeriCodeProps } from '../InputVeriCode';

export interface FormItemWrapperProps<T> {
  style?: CSSProperties;
  wrapperProps: T;
  children?: any;
  className?: string;
  required?: boolean;
  name: string;
  fieldKey: string;
  initialValue?: any;
  // 是否第一次校验
  validateFirst?: boolean;
  label?: string;
  // 是否全为空格
  whitespace?: boolean;
  // 不能为空的提示语
  requiredMessage?: string;
  rules?: Rule[];
}

interface FormItemArgs {
  rules?: Rule[];
}

/**
 * formItem包装器
 * @param Wrapper
 * @param args
 */
export function FormItemWrapper<T>(Wrapper: React.FC<T>, args?: FormItemArgs) {
  return function (props: FormItemWrapperProps<T>) {
    const { rules: arules = [] } = args || {};

    const {
      style,
      wrapperProps,
      children,
      className,
      required,
      name,
      fieldKey,
      initialValue,
      validateFirst = true,
      label,
      rules = [],
      whitespace,
      requiredMessage,
    } = props;

    const innerRuels: Rule[] = [];
    if (whitespace) {
      innerRuels.push({
        whitespace,
        message: requiredMessage || `${label || ''}不能为空`,
      });
    }
    if (required) {
      innerRuels.push({
        required,
        message: requiredMessage || `${label || ''}不能为空`,
      });
    }

    return (
      <Form.Item
        style={style}
        className={className}
        required={required}
        name={name}
        fieldKey={fieldKey}
        initialValue={initialValue}
        validateFirst={validateFirst}
        label={label}
        rules={[...rules, ...arules, ...innerRuels]}
      >
        <Wrapper {...wrapperProps}>{children}</Wrapper>
      </Form.Item>
    );
  };
}

/**
 * 输入限制
 */
export const FormInputLimit = FormItemWrapper<InputLimitProps>(InputLimit);

/**
 * 手机号输入
 */
export const FormPhone = FormItemWrapper<InputLimitProps>(InputLimit, {
  rules: [
    {
      pattern: /^[1][3,5,7,8][0-9]\\d{8}$/,
      message: '手机号码格式不正确',
    },
  ],
});

/**
 * 密码输入框
 */
export const FormPassword = FormItemWrapper<InputLimitProps>(InputLimit, {
  rules: [
    {
      min: 8,
      max: 26,
      message: '密码必须在8~26位之间',
    },
  ],
});

/**
 * 邮箱输入框
 */
export const FormEmail = FormItemWrapper<InputLimitProps>(InputLimit, {
  rules: [
    {
      pattern: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,
      message: '邮箱格式不正确',
    },
  ],
});

/**
 * 验证码输入框
 */
export const FormVeriCode = FormItemWrapper<InputVeriCodeProps>(InputVeriCode);
